<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore, useUserStore } from '@/store'
import { logout } from '@/api/auth'
import { updateUserAvatar, updateUserNickname, updateUserPassword } from '@/api/user'
import { upload } from '@/api/system'
import { customRequest } from '@/utils/file'
const router = useRouter()
const authStore = useAuthStore()
const userStore = useUserStore()
const userInfo = ref({})

// 初始化并获取用户信息
const getNewUserInfo = async () => {
  await userStore.initUserInfoAction()
  const res = await userStore.getUserInfoAction()
  userInfo.value = res
}

// 获取用户信息和公钥
onMounted(async () => {
  await authStore.initPublicKeyAction()
  userInfoForm.value.publicKey = await authStore.getPublicKeyAction()
  await getNewUserInfo()
  userInfoForm.value.id = userInfo.value.id
})

// 修改信息对话框
const isEdit = ref(false)
// 修改信息对话框标题
const modalTitle = ref('')
// 修改信息表单数据
const userInfoForm = ref({
  id: '',
  avatar: '',
  username: '',
  nickname: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  publicKey: ''
})
// 修改信息类别
const editItemId = ref(0)
// 修改信息
const editMsg = (id) => {
  editItemId.value = id
  isEdit.value = true
  switch (id) {
    // 修改头像
    case 0:
      modalTitle.value = '修改头像'
      break
    // 修改密码
    case 1:
      modalTitle.value = '修改密码'
      break
    // 修改昵称
    case 2:
      modalTitle.value = '修改昵称'
      break
  }
}
// 绑定dom元素
const avatarUpdateDom = ref()
const passwordUpdateDom = ref()
const nicknameUpdateDom = ref()
// 清空表单数据和校验结果
const clearForm = (domIten) => {
  domIten.value.resetFields()
  domIten.value.clearValidate()
}
// 校验表单数据
const checkUserInfo = async (domIten) => {
  await domIten.value.validate().then((res) => {
    if (res) {
      return false
    }
  })
  return true
}
// 对修改信息的数据进行校验和赋值
const editUserMsgBeforeOk = async () => {
  let isPass = true
  switch (editItemId.value) {
    case 0:
      // 修改头像没有表单，不需要校验
      break
    case 1:
      // 修改密码
      isPass = await checkUserInfo(passwordUpdateDom)
      break
    case 2:
      // 修改昵称
      isPass = await checkUserInfo(nicknameUpdateDom)
      break
  }
  return isPass
}
// 修改信息对话框确定
const editUserMsgOk = async () => {
  switch (editItemId.value) {
    case 0:
      // 修改头像不需要额外处理
      break
    case 1:
      // 修改密码
      await updateUserPassword(userInfoForm.value)
      clearForm(passwordUpdateDom)
      break
    case 2:
      // 修改昵称
      await updateUserNickname(userInfoForm.value)
      clearForm(nicknameUpdateDom)
      break
  }
  await getNewUserInfo()
}
// 修改信息对话框取消
const editUserMsgCancel = () => {
  switch (editItemId.value) {
    case 0:
      // 修改头像不需要额外处理
      break
    case 1:
      // 修改密码
      passwordUpdateDom.value.resetFields()
      passwordUpdateDom.value.clearValidate()
      break
    case 2:
      // 修改昵称
      nicknameUpdateDom.value.resetFields()
      nicknameUpdateDom.value.clearValidate()
      break
  }
}
// 表单校验规则
const rules = {
  nickname: [{ required: true, message: '新昵称不能为空' }],
  oldPassword: [{ required: true, message: '旧密码不能为空' }],
  newPassword: [{ required: true, message: '新密码不能为空' }],
  confirmPassword: [
    { required: true, message: '确认密码不能为空' },
    {
      validator: (value, cb) => {
        if (value !== userInfoForm.value.newPassword) {
          cb('两次密码输入不一致')
        } else {
          cb()
        }
      }
    }
  ]
}
// 修改头像
const setAvatar = async (op) => {
  // const avatarUrl = await customRequest(op, onProgress)
  // console.log('返回的url', avatarUrl)
  const resUrl = await upload(op)
  userInfoForm.value.avatar = resUrl
  await updateUserAvatar(userInfoForm.value)
  isEdit.value = false
  await getNewUserInfo()
}

//文件上传回调，在每个使用文件上传的组件内单独定制
const onProgress = (progress) => {
  console.log('监听进度:', progress + '%')
}

// 退出登陆
const userLogout = async () => {
  await logout(await authStore.getTokenAction())
  authStore.clearTokenAction()
  router.push('/login')
}
</script>

<template>
  <!-- 修改信息对话框 start （暂未完成）-->
  <a-modal
    v-model:visible="isEdit"
    @ok="editUserMsgOk"
    :on-before-ok="editUserMsgBeforeOk"
    @cancel="editUserMsgCancel"
    :title="modalTitle"
  >
    <!-- 修改头像 -->
    <div v-if="editItemId === 0">
      <a-upload :custom-request="setAvatar" :show-file-list="false" draggable />
    </div>
    <!-- 修改密码 -->
    <div v-else-if="editItemId === 1">
      <a-form :model="userInfoForm" :rules="rules" validate-trigger="blur" ref="passwordUpdateDom">
        <a-form-item label="旧密码" field="oldPassword">
          <a-input v-model="userInfoForm.oldPassword" placeholder="请输入旧密码" />
        </a-form-item>
        <a-form-item label="新密码" field="newPassword">
          <a-input v-model="userInfoForm.newPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item label="确认密码" field="confirmPassword">
          <a-input v-model="userInfoForm.confirmPassword" placeholder="请输入确认密码" />
        </a-form-item>
      </a-form>
    </div>
    <!-- 修改昵称 -->
    <div v-else-if="editItemId === 2">
      <a-form :model="userInfoForm" :rules="rules" validate-trigger="blur" ref="nicknameUpdateDom">
        <a-form-item label="新昵称" field="nickname">
          <a-input v-model="userInfoForm.nickname" placeholder="请输入新昵称" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
  <!-- 修改信息对话框 end -->
  <div class="box-avatar">
    <a-avatar :size="160">
      <img :src="userInfo?.avatar" />
    </a-avatar>
  </div>
  <div class="box-msg-from">
    <div class="box-nickname">{{ userInfo.nickname }}</div>
    <div class="box-username">用户名：{{ userInfo.username }}</div>
    <div class="box-id">id：{{ userInfo.id }}</div>
  </div>
  <div class="box-button-group">
    <a-button @click="editMsg(0)">修改头像</a-button>
    <a-button @click="editMsg(1)">修改密码</a-button>
    <a-button @click="editMsg(2)">修改昵称</a-button>
    <a-button @click="userLogout">退出登陆</a-button>
  </div>
</template>

<style scoped>
.box-avatar {
  margin-top: 60px;
  height: 200px;
}
.box-nickname {
  height: 120px;
  font-size: 64px;
}
.box-button-group {
  margin-top: 60px;
}
.box-button-group button:nth-child(n + 2) {
  margin-left: 40px;
}
</style>
